package foxmob.mooc.course;

import foxmob.mooc.DbAccess;
import foxmob.mooc.persist.tables.*;
import foxmob.mooc.persist.tables.Course;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import spark.Request;
import spark.Response;

import static foxmob.mooc.Utils.getMultipart;
import static spark.Spark.post;

/**
 * Created by mvp on 2017/7/29.
 */
public class CourseBook {
    public static void  init(){
        post("/CB/add",CourseBook::addCourseBook);
        post("CB/getbooks",CourseBook::getbooks);
    }
    public static String addCourseBook(Request req, Response res){
        String[] values = getMultipart(new String[]{"course","book"},req);
        int n=0;
        try{
            DSLContext dsl = DbAccess.getDsl();
            DSLContext dsl1 = DbAccess.getDsl();
            Result<?> result = dsl.insertInto(Coursebook.COURSEBOOK,Coursebook.COURSEBOOK.COURSE
                   ,Coursebook.COURSEBOOK.BOOK)
                    .select(dsl.select(Course.COURSE.ID,Book.BOOK.ID)
                    .from(Course.COURSE,Book.BOOK).where(Course.COURSE.NAME.eq(values[0]))
                    .and(Book.BOOK.NAME.eq(values[1])))
                    .returning(Coursebook.COURSEBOOK.BOOK).fetch();
            for(Record r : result){
                n=r.getValue(Coursebook.COURSEBOOK.BOOK);
                break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  String.format("%d",n);
    }
    public static String getbooks(Request req,Response res){
        String[] values = getMultipart(new String[]{"cid"},req);
        int cid =  Integer.parseInt(values[0]);
        String rs ="";
        try{
            DSLContext dsl = DbAccess.getDsl();
            Result<?> result =dsl.select().from(Book.BOOK)
                    .join(Coursebook.COURSEBOOK)
                    .on(Coursebook.COURSEBOOK.COURSE.eq(cid))
                    .where(Book.BOOK.ID.eq(Coursebook.COURSEBOOK.BOOK))
                    .fetch();
            for(Record r:result){
                String name = r.getValue(Book.BOOK.NAME);
                System.out.println(name);
                String s =  String.format("\"%s\",",name);
                rs = String.format("%s%s",rs,s);
            }
                rs = String.format("{%s\"\"}",rs);
        }catch (Exception e){
            e.printStackTrace();
        }
        return rs;
    }
}
